package com;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

public class SimpleEmbedTomcatServer {

	// http://localhost:8081/test
	// http://localhost:8081/testa
	public static void main(String[] args) throws LifecycleException {
		//把目录的绝对的路径获取到
        String classpath = System.getProperty("user.dir");
        System.out.println(classpath);
        //D:\workspace-tomcat\tomcat-maven
        //我们new一个Tomcat
         Tomcat tomcat = new Tomcat();

         //设置Tomcat的端口tomcat.setPort(9091)。两种写法都可以设置端口
         Connector connector = tomcat.getConnector();
         connector.setPort(8081);
         //设置Host
         Host host = tomcat.getHost();
         //我们会根据xml配置文件来
         host.setName("localhost");
         host.setAppBase("webapps");
         //前面的那个步骤只是把Tomcat起起来了，但是没啥东西
         //要把class加载进来，把启动的工程加入进来了
         Context context = tomcat.addContext(host, "/", classpath);

         if(context instanceof StandardContext){
             StandardContext standardContext = (StandardContext) context;
             //我们要把Servlet设置进去
             Wrapper wrapper =  tomcat.addServlet("/", "DemoServlet", new DemoServlet());
             Wrapper wrapper2 =  tomcat.addServlet("/", "DemoAsyncServlet", new DemoAsyncServlet());
             wrapper2.setAsyncSupported(true);
             wrapper.addMapping("/test");
             wrapper2.addMapping("/testa");
         }
         //Tomcat跑起来
         tomcat.start();
         //强制Tomcat server等待，避免main线程执行结束后关闭
         tomcat.getServer().await();
	}

}